package xdu.lz.stage1_basic.chapter1_threadsafe.lock;

import java.util.Collection;

public class TestMyLock {
    public static void main(String[] args) throws InterruptedException {
        final Lock myLock = new MyLock();
        Collection<Thread> blockThreads;
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
//                    myLock.chapter2_caslock();
                    myLock.tryLock(20L);
                    work();
//                    myLock.getBlockedThread().
//                            forEach(t-> System.out.println(t.getName()));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                catch (Lock.TimeOutException e){
                    System.out.println(e.getMessage());
                }
                finally {
                    //确保什么情况下都要释放锁
                    myLock.unlock();
                }
            },"thread"+i).start();
        }
        Thread.sleep(100);
        //是main线程释放，应该被阻止
        myLock.unlock();
    }

    public static void work(){
        System.out.println(Thread.currentThread().getName()+ " take the chapter2_caslock and working...");
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
